//
//  Utility.m
//  Project
//
//  Created by 本游网络 on 2017/12/8.
//  Copyright © 2017年 本游网络. All rights reserved.
//

#import "Utility.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "NSData+Extension.h"
#import "NSDateFormatter+Extension.h"

@implementation Utility

+ (NSDateFormatter *)dateFormatter{
    static NSDateFormatter *fmt = nil;
    /// 由于NSDateFormatter 有一定的性能问题 故全局共享一个
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
        ///  真机调试的时候，必须加上这句
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    });
    return fmt;
}


+ (BOOL)isAppInReview {
//    if (DEBUG) {
        return YES;
//    } else {
//        return [[NSUserDefaults standardUserDefaults] boolForKey:@"AppInReview"];
//    }
}

+ (BOOL)isValidDictionary:(id)object {
    return object && [object isKindOfClass:[NSDictionary class]] && ((NSDictionary *)object).count;
}

+ (BOOL)isValidArray:(id)object {
    return object && [object isKindOfClass:[NSArray class]] && ((NSArray *)object).count;
}

+ (BOOL)isValidString:(id)object {
    return object && [object isKindOfClass:[NSString class]] && ((NSString *)object).length;
}

+ (BOOL)isValidNumber:(id)object {
    return object && [object isKindOfClass:[NSNumber class]];
}

+ (UITabBarController *)currentTabBarController {
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([controller isKindOfClass:[UITabBarController class]]) {
        return (UITabBarController *)controller;
    }
    return nil;
}

+ (UINavigationController *)currentNavigationController {
    UITabBarController *tabBarController = [self currentTabBarController];
    if (tabBarController) {
        UINavigationController *controller = tabBarController.selectedViewController;
        if (controller) {
            return controller;
        } else {
            return tabBarController.viewControllers.firstObject;
        }
    }
    return nil;
}

+ (NSString *)currentWWANType {
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *currentRadioAccessTechnology = info.currentRadioAccessTechnology;
    NSString *type = @"Unknown";
    
    if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] ||
        [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] ||
        [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
        type = @"2G";
    } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
               [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
        type = @"3G";
    } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
        type = @"4G";
    }
    
    return type;
}

+ (BOOL)isMobileNumber:(NSString *)phone{
    //手机号简单校验，以13， 15，18开头，八个 \d 数字字符
    
    NSString *phoneRegex = @"^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    
    return [phoneTest evaluateWithObject:phone];
    
}
+(BOOL)isEmailWithString:(NSString *)string
{
    
    NSString *phoneRegex = @"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
    
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    
    return [phoneTest evaluateWithObject:string];
}
+ (NSDictionary *)transformURLQuery:(NSString *)query {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if ([Utility isValidString:query]) {
        for (NSString *param in [query componentsSeparatedByString:@"&"]) {
            NSArray *elts = [param componentsSeparatedByString:@"="];
            if ([elts count] < 2) continue; // Invalid parameter
            NSString *key = elts.firstObject;
            parameters[key.lowercaseString] = elts.lastObject;
        }
    }
    return parameters;
}


+ (NSString *)binaryUnitTransform:(long long)value withUnit:(BinaryUnit)unit {
    if (value < 1.0 && value > 0 && unit > b) {
        return [self binaryUnitTransform:value * 1024.0 withUnit:--unit];
    }
    else if (value >= 1024.0 && unit < YB) {
        return [self binaryUnitTransform:value / 1024.0 withUnit:++unit];
    }
    else {
        NSDictionary *units = @{
                                @(b): @"b",
                                @(B): @"B",
                                @(KB): @"K",
                                @(MB): @"M",
                                @(GB): @"G",
                                @(TB): @"T",
                                @(PB): @"P",
                                @(ZB): @"Z",
                                @(YB): @"Y"
                                };
        return [NSString stringWithFormat:@"%lld%@", value, units[@(unit)]];
    }
}


+(NSString *)dateToOld:(NSDate *)bornDate{
    //获得当前系统时间
    NSDate *currentDate = [NSDate date];
    //获得当前系统时间与出生日期之间的时间间隔
    NSTimeInterval time = [currentDate timeIntervalSinceDate:bornDate];
    //时间间隔以秒作为单位,求年的话除以60*60*24*356
    NSInteger age = ((NSInteger)time)/(3600*24*365);
    return [NSString stringWithFormat:@"%ld",age];
}
+(NSString *)getZZwithString:(NSString *)string{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n"
                                                                                    options:0
                                                                                      error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}

@end
